<template>
  <el-dialog
      title="模板库预览"
      :center="true"
      :lock-scroll="true"
      :with-header="false"
      :visible.sync="visible"
      :before-close="()=>handleClose()"
      :custom-class="getDevTypeSize"
  >
    <div class="layer_inside" :key="uuid">
      <div class="layer_header">
        <span class="title">模板库预览</span>
        <i class="el-icon-close" @click="()=>handleClose()"/>
      </div>
      <div class="layer_main_wrap" v-loading="loading">
        <div class="layer_delete_main">
          <!--通过组件生成预览-->
          <div class="preView vhView" ref="preViewRef">
            <div class="cvsWin" id="screen-info" ref="cvsRef">
              <iframe
                  class="scrollbar"
                  id="scrollbar"
                  ref="iframe"
                  scrolling="none"
                  :width="iframeSize.width"
                  :height="iframeSize.height"
                  :src="`/clinic/api/irms/file/view?filePath=${htmlPath}&t=${uuid}&devType=2`"
                  @load="handleLoaded(this)"/>
            </div>
          </div>
        </div>
        <div class="layer_delete_bottom">
          <el-button class="button_item cancel" @click="()=>handleClose()">取消</el-button>
          <el-button
              type="primary"
              class="button_item sure"
              @click="()=>handleSure()">
            确认
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import lodash from "lodash";
import {v4 as uuid} from 'uuid';
import {pxToVw} from "@/utils/common";
import html2canvas from "html2canvas";
import {ModelDesignApi} from "@/api/modeldesign";

export default {
  name: "TemplatePreview",

  props: ["visible", 'info', 'resolution', 'htmlPath'],

  components: {},

  data() {
    return {
      uuid: '',
      number: true,
      loading: false,
      observer: null,
      iframeSize: {
        height: "100%",
        width: 'auto'
      },
    };
  },

  computed: {
    // 设备信息
    getDevTypeSize() {
      let {width} = this.resolution;
      switch (width) {
        case '1920':
          return `layer_wrap template_preview_layer layer-preview-1920`;
        case '1080':
          return `layer_wrap template_preview_layer layer-preview-1080`;
        default:
          return `layer_wrap template_preview_layer layer-preview-1080`;
      }
    },
  },

  mounted() {
    const self = this;
    window.addEventListener('resize', lodash.throttle(() => {
      self.changeCanvas()
    }, 2000))
  },

  methods: {
    // 计算视图
    getScaleSize(width = 1920, height = 1080) {
      const self = this;
      /*
       用视口当前的宽高除以设计图宽高，如果小于1表示屏幕缩小了，反之屏幕放大了，那scale也就应该进行对应的放大或缩小，并且缩放时宽高应该是等比例缩放。
       如果 ww = wh 表示屏幕是在根据设计图宽高等比例缩放。
       如果 ww < wh 表示在等比缩放基础上宽度更小，为了让所有内容都能居中显示在屏幕中，就需要scale按照ww这个比例来缩放宽高。
       如果 ww > wh 表示在等比缩放基础上高度更小，为了让所有内容都能居中显示在屏幕中，就需要scale按照wh这个比例来缩放宽高。
       口诀：基于设计图宽高比，实时视口 宽更小就使用 视口宽/设计图宽 的比值来等比缩放。高更小就使用 视口高/设计图高 的比值来等比缩放
   */
      let targetX = 1920;
      let targetY = 1080;
      let targetRatio = 16 / 9;
      let sideX = 0;
      let sideY = 0;
      let currentX = self.$refs?.preViewRef?.offsetWidth || 1920;
      let currentY = self.$refs?.preViewRef?.offsetHeight || 1080;
      // number > 100 && number < 200 currentX >= 1320
      if (currentX >= 1320 && currentX < 1920) {
        sideX = 620
        sideY = 60
      } else if(currentX >= 1922) {
        sideX = 1220
        sideY = 600
      }else {
        sideX = 80
        sideY = 60
      }
      let offsetWidth = currentX - sideX;
      let offsetHeight = currentY - sideY;
      const ww = parseInt(offsetWidth) / parseInt(width);
      const wh = parseInt(offsetHeight) / parseInt(height);
      return ww < wh ? ww : wh
    },

    // 计算画布
    changeCanvas() {
      const self = this;
      let {width, height} = self.resolution;
      let offsetWidth = self.$refs?.preViewRef?.offsetWidth - 60;
      let offsetHeight = self.$refs?.preViewRef?.offsetHeight - 60;
      if ((self.$refs.cvsRef)) {
        self.$nextTick(() => {
          let scale = self.getScaleSize(parseInt(width), parseInt(height), offsetWidth, offsetHeight);
          if (scale < 0) {
            scale = 0.1
          }
          self.$refs.cvsRef.style.transform = `scale(${scale}) translate(-50%, -50%)`;
          self.$refs.cvsRef.style.width = `${pxToVw(parseInt(width))}`;
          self.$refs.cvsRef.style.height = `${pxToVw(parseInt(height))}`;
          // 获取 iframe 对象-修改iframe的fontSize信息
          const myFrame = self.$refs.iframe;
          let rem = (this.$utils.setHTMLFontSize())
          myFrame.contentDocument.documentElement.style.fontSize = `${rem}`
        })
      }
    },

    //iframe加载完成
    handleLoaded(e) {
      const self = this;
      self.number = false;
      self.$nextTick(() => {
        self.loading = false;
        const myFrame = self.$refs.iframe; // 获取 iframe 对象
        let rem = (this.$utils.setHTMLFontSize())
        myFrame.contentDocument.documentElement.style.fontSize = `${rem}`
        self.changeCanvas()
      })
    },

    // 保存-生成图片
    handleSure() {
      const self = this;
      const myFrame = self.$refs.iframe; // 获取 iframe 对象
      if (myFrame) {
        try {
          const frameWindow = myFrame.contentWindow || myFrame.contentDocument.defaultView; // 获取 iframe 的 window 对象
          if (frameWindow && typeof frameWindow === 'object') {
            let subWeb = myFrame ? myFrame?.contentDocument.querySelector('.canvasDom') : '';
            html2canvas(subWeb, {
              backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
              useCORS: true, //支持图片跨域
              scale: 0.5, //设置放大的倍数
            }).then(async (canvas) => {
              // 把生成的base64位图片上传到服务器,生成在线图片地址
              let base64Img = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64
              let params = Object();
              Reflect.set(params, 'coverBase64', base64Img);
              Reflect.set(params, 'id', this.info)
              let {code, msg} = await ModelDesignApi.release(params);
              if (code === 200) {
                self.handleClose();
                await self.$router.push({
                  path: '/template'
                });
              } else {
                this.$message({
                  message: `${msg}`,
                  type: 'warning'
                });
              }
            });
          } else {
            console.error('无法获取 iframe 的 window 对象');
          }
        } catch (e) {
          console.error('发生错误', e);
        }
      } else {
        console.error('未能找到指定的 iframe');
      }
    },

    // 关闭
    handleClose() {
      this.$emit("handleCancel", false);
    },

  },

  watch: {
    // 初始化
    visible: {
      handler(val) {
        const self = this;
        if (val) {
          self.uuid = uuid();
          self.loading = true;
        }
      },
      deep: true,
      immediate: true,
    }
  }

};
</script>

<style lang="scss" scoped>
@import "@/components/assets/style/layer";
@import "./assets/style";
</style>